/**
 * 浏览器通知工具
 */
class NotificationManager {
  constructor() {
    this.permission = null
    this.notificationHistory = [] // 通知历史记录
    this.maxHistorySize = 100 // 最多保存100条历史记录
    this.loadHistory()
    this.checkPermission()
  }

  /**
   * 从localStorage加载通知历史
   */
  loadHistory() {
    try {
      const saved = localStorage.getItem('notification_history')
      if (saved) {
        this.notificationHistory = JSON.parse(saved)
      }
    } catch (error) {
      console.error('加载通知历史失败:', error)
      this.notificationHistory = []
    }
  }

  /**
   * 保存通知历史到localStorage
   */
  saveHistory() {
    try {
      // 只保存最近100条
      const toSave = this.notificationHistory.slice(-this.maxHistorySize)
      localStorage.setItem('notification_history', JSON.stringify(toSave))
    } catch (error) {
      console.error('保存通知历史失败:', error)
    }
  }

  /**
   * 添加通知到历史记录
   */
  addToHistory(notification) {
    const historyItem = {
      id: notification.id || Date.now(),
      title: notification.title,
      body: notification.body,
      timestamp: new Date().toISOString(),
      type: notification.type || 'reminder',
      reminderId: notification.reminderId,
      itineraryId: notification.itineraryId,
      read: false
    }
    this.notificationHistory.unshift(historyItem)
    this.saveHistory()
    return historyItem
  }

  /**
   * 获取通知历史
   */
  getHistory(limit = 50) {
    return this.notificationHistory.slice(0, limit)
  }

  /**
   * 标记通知为已读
   */
  markAsRead(notificationId) {
    const notification = this.notificationHistory.find(n => n.id === notificationId)
    if (notification) {
      notification.read = true
      this.saveHistory()
    }
  }

  /**
   * 标记所有通知为已读
   */
  markAllAsRead() {
    this.notificationHistory.forEach(n => {
      n.read = true
    })
    this.saveHistory()
  }

  /**
   * 获取未读通知数量
   */
  getUnreadCount() {
    return this.notificationHistory.filter(n => !n.read).length
  }

  /**
   * 清除通知历史
   */
  clearHistory() {
    this.notificationHistory = []
    this.saveHistory()
  }

  /**
   * 检查通知权限
   */
  checkPermission() {
    if (!('Notification' in window)) {
      console.warn('此浏览器不支持通知功能')
      this.permission = 'unsupported'
      return false
    }

    this.permission = Notification.permission
    return this.permission === 'granted'
  }

  /**
   * 请求通知权限
   */
  async requestPermission() {
    if (!('Notification' in window)) {
      return Promise.resolve(false)
    }

    if (this.permission === 'granted') {
      return Promise.resolve(true)
    }

    if (this.permission === 'denied') {
      return Promise.resolve(false)
    }

    try {
      const permission = await Notification.requestPermission()
      this.permission = permission
      return permission === 'granted'
    } catch (error) {
      console.error('请求通知权限失败:', error)
      return false
    }
  }

  /**
   * 显示通知
   * @param {string} title - 通知标题
   * @param {Object} options - 通知选项
   */
  async showNotification(title, options = {}) {
    // 检查权限
    if (!this.checkPermission()) {
      // 尝试请求权限
      const granted = await this.requestPermission()
      if (!granted) {
        console.warn('通知权限未授予')
        return null
      }
    }

    const defaultOptions = {
      body: '',
      icon: '/favicon.ico',
      badge: '/favicon.ico',
      tag: 'itinerary-reminder',
      requireInteraction: false,
      silent: false,
      ...options
    }

    try {
      const notification = new Notification(title, defaultOptions)

      // 设置点击事件
      notification.onclick = (event) => {
        event.preventDefault()
        window.focus()
        // 可以在这里添加跳转逻辑
        if (options.onClick) {
          options.onClick(event)
        }
        notification.close()
      }

      // 设置关闭事件
      notification.onclose = () => {
        if (options.onClose) {
          options.onClose()
        }
      }

      // 自动关闭（如果设置了时间）
      if (options.duration) {
        setTimeout(() => {
          notification.close()
        }, options.duration)
      }

      return notification
    } catch (error) {
      console.error('显示通知失败:', error)
      return null
    }
  }

  /**
   * 显示行程提醒通知
   * @param {Object} reminder - 提醒数据
   */
  async showReminderNotification(reminder) {
    const title = '行程提醒'
    const body = reminder.message || `您的行程"${reminder.itinerary_title || reminder.itinerary?.title}"有新的提醒`

    // 添加到历史记录
    const historyItem = this.addToHistory({
      title,
      body,
      type: 'reminder',
      reminderId: reminder.id,
      itineraryId: reminder.itinerary?.id || reminder.itinerary_id
    })

    const notification = await this.showNotification(title, {
      body,
      icon: '/favicon.ico',
      tag: `reminder-${reminder.id}`,
      requireInteraction: true,
      onClick: () => {
        // 标记为已读
        this.markAsRead(historyItem.id)
        // 跳转到行程详情页面
        if (window.location.pathname !== '/itineraries') {
          window.location.href = '/itineraries'
        }
      }
    })

    return notification
  }

  /**
   * 关闭所有通知
   */
  closeAll() {
    // 注意：浏览器API不提供直接关闭所有通知的方法
    // 但可以通过tag来管理
    console.log('无法直接关闭所有通知，请手动关闭')
  }
}

// 创建全局实例
const notificationManager = new NotificationManager()

export default notificationManager

